package SocketBaseTest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by yexuan on 2018/3/22.
 * 用线程实现udp聊天
 * UDP聊天软件
 有接收与发送的功能
 因为接收与发送可以同时执行
 所以需要使用多线程技术
 又因为接收和发送的数据的内容不同
 所以要定义在不同的类中
 */

class ChatSend2 implements Runnable{
    private DatagramSocket ds;

    public ChatSend2(DatagramSocket ds){
        this.ds = ds;
    }

    @Override
    public void run() {
        try {
          while (true){
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              String line = null;
              while((line=br.readLine())!=null){
                  if("886".equals(line))
                      break;
                  byte[] bytes = line.getBytes();
                  DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getLocalHost(),10001);
                  ds.send(dp);
              }
          }
        }catch (Exception e) {
           throw new RuntimeException(e);
        }
    }
}

class ChatReceive2 implements Runnable{
    private DatagramSocket ds;

    public ChatReceive2(DatagramSocket ds){
        this.ds = ds;
    }

    @Override
    public void run() {
        try {
            while (true){
                byte[] bytes = new byte[1024];
                DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
                ds.receive(dp);
                String ip = dp.getAddress().getHostAddress();
                System.out.println(ip+".........."+new String(dp.getData(),0,dp.getLength()));
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
public class ChatDemo{
    public static void main(String[] args) throws Exception{
        DatagramSocket  ds1 = new DatagramSocket();
        DatagramSocket ds2 = new DatagramSocket(10001);
        new Thread(new ChatSend2(ds1)).start();
        new Thread(new ChatReceive2(ds2)).start();
    }
}
